//
//  MainViewController.m
//  Games
//
//  Created by iOS Two on 14/12/23.
//  Copyright (c) 2014年 iOS Two. All rights reserved.
//

#import "MainViewController.h"
#import "EmotionViewController.h"
#import "EmotionDeatilViewController.h"
#import "myObj.h"
#import "myData.h"
#import "MJRefresh.h"

@interface MainViewController ()

@end

@implementation MainViewController
-(void)viewWillAppear:(BOOL)animated {
    [self findSQL];
    int count;
    if (_collectGifName.count > 5) {
        count = 5;
    } else {
        count = _collectGifName.count;
    }
    for (UIView *view in [_scroll subviews]) {
        [view removeFromSuperview];
    }
    if (_scroll == nil) {
        _scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 114, kwidth, 145)];
        _scroll.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_scroll];
        if (kwidth == 320) {
            _scroll.frame = CGRectMake(0, 64 + 39, kwidth, 111);
        } else if (kwidth == 375) {
            _scroll.frame = CGRectMake(0, 64 + 45, kwidth, 105);
        }
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    for (int i = 0; i < count; i++) {
        UIImageView *image = [[UIImageView alloc]init];
        image.layer.cornerRadius = 7;
        image.layer.masksToBounds = YES;
        NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.gif",[_collectGifCover objectAtIndex:i]]];
        image.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:uniquePath]];
        image.userInteractionEnabled = YES;
        [_scroll addSubview:image];
        UIButton *tapButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [tapButton addTarget:self action:@selector(lookMyEmotion:) forControlEvents:UIControlEventTouchUpInside];
        tapButton.backgroundColor = [UIColor clearColor];
        tapButton.tag = i;

        UILabel *label = [[UILabel alloc]init];
        label.text = [_collectGifName objectAtIndex:i];
        label.textColor = [UIColor colorWithRed:0.96 green:0.55 blue:0.08 alpha:1];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont fontWithName:@"MFYaYuan_Noncommercial-Regular" size:12];
        [_scroll addSubview:label];
        
        if (kwidth == 414) {
            image.frame = CGRectMake(25 + (25 + 86) * i, 20, 86, 86);
            label.frame = CGRectMake(25 + (25 + 86) * i, 115, 86, 20);
            _scroll.contentSize = CGSizeMake(25 + (25 + 86) * count, 145);
        } else if (kwidth == 320) {
            image.frame = CGRectMake(22 + (22 + 67) * i, 16, 67, 67);
            label.frame = CGRectMake(22 + (22 + 67) * i, 88, 67, 20);
            _scroll.contentSize = CGSizeMake(22 + (22 + 67) * count, 111);
        } else if (kwidth == 375) {
            image.frame = CGRectMake(22 + (22 + 67) * i, 16, 67, 67);
            label.frame = CGRectMake(22 + (22 + 67) * i, 85, 67, 20);
            _scroll.contentSize = CGSizeMake(22 + (22 + 78) * count, 87);
        }
        [tapButton setFrame:CGRectMake(0, 0, image.frame.size.width, image.frame.size.height)];
        [image addSubview:tapButton];
    }
    
}
-(void)lookMyEmotion:(id)sender {
    UIButton *button = (UIButton *)sender;
    EmotionDeatilViewController *emotionDea = [[EmotionDeatilViewController alloc] init];
    
    emotionDea.gifName = [_collectGifName objectAtIndex:button.tag];
    [self.navigationController pushViewController:emotionDea animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getData];
    [self creatController];
    self.navigationItem.title = @"微表情";

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
    label.text = @"微表情";
    label.font = [UIFont fontWithName:@"MFYaYuan_Noncommercial-Regular" size:20];
    label.textColor = [UIColor colorWithRed:0.98 green:0.59 blue:0.16 alpha:1];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:1 green:0.96 blue:0.62 alpha:1];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.98 green:0.59 blue:0.18 alpha:1];
}
-(void)findSQL {
    _collectHasName = [[NSMutableArray alloc]init];
    _collectGifName = [[NSMutableArray alloc]init];
    _collectGifCover = [[NSMutableArray alloc]init];
    myData *data = [[myData alloc]init];
    [data initData];
    NSArray *array = [data selectData];
    for (int i = 0; i < array.count; i++) {
        myObj *obj = [array objectAtIndex:i];
        [_collectGifName addObject:obj.gifName];
        [_collectGifCover addObject:obj.gifImage];
        [_collectHasName addObject:[NSNumber numberWithInt:obj.hasName]];
    }
    NSLog(@"%@",_collectGifCover);
}
-(void)getData {
    [_collection removeFooter];
    [_collection addFooterWithTarget:self action:@selector(footerRereshing)];
    _showNum = 9;
    _gifImage = [[NSMutableArray alloc]init];
    _gifUrl = [[NSMutableArray alloc]init];
    _gifName = [[NSMutableArray alloc]initWithObjects:@"蜡笔小新",@"Hello Kitty",@"甜甜私房猫", nil];
    _gifCover = [[NSMutableArray alloc]initWithObjects:@"哆啦A梦—0",@"hello kitty_0",@"甜甜私房猫-0", nil];
    _hasNameArray = [[NSMutableArray alloc]initWithObjects:[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],nil];
    for (int i = 0; i < _gifCover.count; i++) {
        NSString *path = [[NSBundle mainBundle] pathForResource:[_gifCover objectAtIndex:i] ofType:@"png"];
        NSData *gifData = [NSData dataWithContentsOfFile:path];
        [_gifImage addObject:gifData];
    }
    [self showIndeterminateProgress];
    AVQuery *query = [[AVQuery alloc]initWithClassName:@"BiaoQingBao"];
    [query orderByAscending:@"sort"];
    query.limit = 9;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error == nil) {
            for (int i = 0 ; i < objects.count; i++) {
                AVFile *file = [[objects objectAtIndex:i] objectForKey:@"gifCover"];
                NSData *data = [file getData];
                [_gifImage addObject:data];
                
                [_gifName addObject:[[objects objectAtIndex:i] objectForKey:@"gifName"]];
                [_hasNameArray addObject:[[objects objectAtIndex:i] objectForKey:@"hasName"]];
            }
            [HUD hide:YES];
            [_collection reloadData];
            [_collection headerEndRefreshing];
        } else {
            [HUD hide:YES];
            [self alertViewShow:@"网络加载失败"];
            [_collection headerEndRefreshing];
        }
    }];
}

-(void)goMyEmotion:(id)sender {
    MyEmotionViewController *myEmotionVC = [[MyEmotionViewController alloc] init];
    [self.navigationController pushViewController:myEmotionVC animated:YES];
}

-(void)creatController {
    UIImage *back = [UIImage imageNamed:@"abc"];
    UIImageView *backView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, kwidth, back.size.height * kwidth / back.size.width)];
    backView.image = back;
    [self.view addSubview:backView];
    
    UIImage *all = [UIImage imageNamed:@"chakan_03"];
    UIButton *allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    allButton.frame = CGRectMake(kwidth - 110, 80, all.size.width, all.size.height);
    [allButton addTarget:self action:@selector(goMyEmotion:) forControlEvents:UIControlEventTouchUpInside];
    [allButton setBackgroundImage:all forState:UIControlStateNormal];
    [self.view addSubview:allButton];
    
    if (kwidth == 320) {
        allButton.frame = CGRectMake(kwidth - 110, 71, all.size.width, all.size.height);
    } else if (kwidth == 375) {
        allButton.frame = CGRectMake(kwidth - 110, 75, all.size.width, all.size.height);
    }
    
    KRLCollectionViewGridLayout *layout = [[KRLCollectionViewGridLayout alloc]init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    _collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64 + back.size.height, kwidth, kHeight - 64 - back.size.height  ) collectionViewLayout:layout];
    [_collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    //设置代理
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.backgroundColor = [UIColor colorWithRed:1 green:0.97 blue:0.84 alpha:1];
    [self.view addSubview:_collection];
    
    self.layout.numberOfItemsPerLine = 3;
    self.layout.aspectRatio = 1;
    self.layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    if (kwidth == 320) {
        self.layout.sectionInset = UIEdgeInsetsMake(10, 0, 0, 0);
        self.layout.aspectRatio = 1/1.1;
    } else if (kwidth == 375) {
        self.layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
        self.layout.aspectRatio = 1/1.05;
    }
    self.layout.interitemSpacing = 0;
    self.layout.lineSpacing = -10;
    
    [_collection addFooterWithTarget:self action:@selector(footerRereshing)];
    [_collection addHeaderWithTarget:self action:@selector(headerRefreshing)];
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _collection.headerPullToRefreshText = @"下拉可以刷新了";
    _collection.headerReleaseToRefreshText = @"松开马上刷新了";
    _collection.headerRefreshingText = @"正在刷新中";
    
    _collection.footerPullToRefreshText = @"上拉可以加载更多数据了";
    _collection.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    _collection.footerRefreshingText = @"正在加载中";
}
-(void)headerRefreshing {
    [self getData];
}
- (void)footerRereshing {
    AVQuery *query = [[AVQuery alloc]initWithClassName:@"BiaoQingBao"];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    [query orderByAscending:@"sort"];
    query.limit = 9;
    query.skip = _showNum;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error == nil) {
            if (objects.count < 6) {
                [_collection removeFooter];
            }
            for (int i = 0 ; i < objects.count; i++) {
                AVFile *file = [[objects objectAtIndex:i] objectForKey:@"gifCover"];
                NSData *data = [file getData];
                [_gifImage addObject:data];
                
                [_gifName addObject:[[objects objectAtIndex:i] objectForKey:@"gifName"]];
                [_hasNameArray addObject:[[objects objectAtIndex:i] objectForKey:@"hasName"]];
                
            }
            [HUD hide:YES];
            [_collection footerEndRefreshing];
            [_collection reloadData];
        } else {
            [HUD hide:YES];
            [_collection footerEndRefreshing];
            [self alertViewShow:@"网络加载失败"];
        }
    }];
    _showNum = _showNum + 9;

}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _gifImage.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identify = @"cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    if (!cell) {
        
    } else {
        for (UIView *view in [cell.contentView subviews]) {
            [view removeFromSuperview];
        }
    }
//    cell.backgroundColor = [UIColor whiteColor];
    UIView *back = [[UIView alloc]initWithFrame:CGRectMake(13, 10, 100, 100)];
    back.backgroundColor = [UIColor whiteColor];
    back.layer.cornerRadius = 5;
    back.layer.borderColor = [[UIColor colorWithRed:0.92 green:0.88 blue:0.5 alpha:1] CGColor];
    back.layer.borderWidth = 1;
    back.layer.shadowColor = [UIColor colorWithRed:0.73 green:0.73 blue:0.73 alpha:1].CGColor;
    back.layer.shadowOffset = CGSizeMake(1, 1);
    back.layer.shadowOpacity = 0.5;
    back.layer.shadowRadius = 1.0;
    [cell.contentView addSubview:back];
    
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(5, 4, 91, 91)];
    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 80, 100, 20)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, 81, 91, 17)];
    if (_gifImage.count > 3) {
        image.image = [UIImage imageWithData:[_gifImage objectAtIndex:indexPath.row]];
        image.layer.cornerRadius = 5;
        image.layer.masksToBounds = YES;
        [back addSubview:image];
        
        line.backgroundColor = [UIColor whiteColor];
        line.layer.cornerRadius = 5;
        line.layer.masksToBounds = YES;
        [back addSubview:line];
        
        label.text = [_gifName objectAtIndex:indexPath.row];
        label.textColor = [UIColor colorWithRed:0.96 green:0.55 blue:0.15 alpha:1];
        label.font = [UIFont fontWithName:@"MFYaYuan_Noncommercial-Regular" size:12];
        label.textAlignment = NSTextAlignmentCenter;
        [back addSubview:label];
    }
    
    if (kwidth == 320) {
        back.frame = CGRectMake(7, 10, 90, 90);
        image.frame = CGRectMake(5, 4, 81, 81);
        line.frame = CGRectMake(0, 70, 90, 20);
        label.frame = CGRectMake(0, 71, 90, 17);
    } else if (kwidth == 375) {
        back.frame = CGRectMake(10, 10, 100, 100);
    }
    return cell;
}
- (KRLCollectionViewGridLayout *)layout {
    return (KRLCollectionViewGridLayout *)_collection.collectionViewLayout;
}
//点击元素触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EmotionViewController *emotion = [[EmotionViewController alloc]init];
    emotion.gifName = [_gifName objectAtIndex:indexPath.row];
    emotion.hasName = [[_hasNameArray objectAtIndex:indexPath.row] boolValue];
    [self.navigationController pushViewController:emotion animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
